<template>
  <el-dialog v-model="dialogVisible" title="编辑调查" width="50%">
    <el-form :model="surveyForm" label-width="120px" class="demo-ruleForm">
      <el-form-item label="调查标题" prop="title">
        <el-input v-model="surveyForm.title" placeholder="请输入调查标题"/>
      </el-form-item>

      <el-form-item label="金额" prop="amount">
        <el-input-number v-model="surveyForm.amount" :min="0" placeholder="请输入金额"></el-input-number>
      </el-form-item>

      <el-form-item label="数量" prop="quantity">
        <el-input-number v-model="surveyForm.quantity" :min="0" placeholder="请输入数量"></el-input-number>
      </el-form-item>

      <el-form-item label="单价" prop="unitPrice">
        <el-input-number v-model="surveyForm.unitPrice" :min="0" placeholder="请输入单价"></el-input-number>
      </el-form-item>

      <el-form-item label="总折扣价" prop="totalDiscountPrice">
        <el-input-number v-model="surveyForm.totalDiscountPrice" :min="0" placeholder="请输入总折扣价"></el-input-number>
      </el-form-item>

      <el-form-item label="条件" prop="condition">
        <el-input v-model="surveyForm.condition" placeholder="请输入条件"></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input v-model="surveyForm.content" type="textarea" placeholder="请输入内容" :rows="4"></el-input>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input v-model="surveyForm.description" type="textarea" placeholder="请输入描述" :rows="4"></el-input>
      </el-form-item>

      <el-form-item label="参与人数" prop="participantCount">
        <el-input-number v-model="surveyForm.participantCount" :min="0" placeholder="请输入参与人数"></el-input-number>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="surveyForm.createTime" type="datetime" placeholder="请选择创建时间"></el-date-picker>
      </el-form-item>

      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="surveyForm.endTime" type="datetime" placeholder="请选择结束时间"></el-date-picker>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="surveyForm.status" placeholder="请选择状态">
          <el-option label="进行中" value="ongoing"></el-option>
          <el-option label="已结束" value="ended"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 表格 -->
  <el-table :data="surveyData" style="width: 100%">
    <el-table-column prop="surveyId" label="调查 ID" width="100"></el-table-column>
    <el-table-column prop="amount" label="金额" width="120"></el-table-column>
    <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
    <el-table-column prop="unitPrice" label="单价" width="120"></el-table-column>
    <el-table-column prop="totalDiscountPrice" label="总折扣价" width="150"></el-table-column>
    <el-table-column prop="title" label="标题" width="200"></el-table-column>
    <el-table-column prop="condition" label="条件"></el-table-column>
    <el-table-column prop="content" label="内容"></el-table-column>
    <el-table-column prop="creatorId" label="创建者 ID" width="120"></el-table-column>
    <el-table-column prop="participantCount" label="参与人数" width="150"></el-table-column>
    <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
    <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
    <el-table-column prop="status" label="状态" width="120">
      <template #default="scope">
        <span v-if="scope.row.status === 'ongoing'">进行中</span>
        <span v-else>已结束</span>
      </template>
    </el-table-column>
    <el-table-column prop="description" label="描述"></el-table-column>

    <!-- 操作列（编辑、删除、详情按钮） -->
    <el-table-column label="操作" fixed="right" width="250" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button size="small" @click="handleView(scope.row)">详情</el-button>
        <el-button size="small" type="danger" @click="deleteSurvey(scope.row.surveyId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 创建按钮 -->
  <el-button type="success" @click="handleCreate">创建调查</el-button>
</template>

<script setup lang="ts">
import {defineProps, ref, reactive, onMounted, watch} from 'vue';
import { ElMessage } from 'element-plus';
import instance from "@/utils/http";
import {useRouter} from "vue-router";
import {useAuthStore} from "@/stores/auth";


const authStore = useAuthStore();

const props = defineProps({
  isEnd:Boolean
})

interface Survey {
  surveyId: number;
  amount: number;
  quantity: number;
  unitPrice: number;
  totalDiscountPrice: number;
  title: string;
  condition: string;
  content: string;
  creatorId: number;
  participantCount: number;
  createTime: string;
  endTime: string;
  status: string;
  description: string;
  createType:string;
}

const surveyData = ref<Survey[]>([]);

const surveyForm = reactive({
  surveyId: 0,
  amount: 0,
  quantity: 0,
  unitPrice: 0,
  totalDiscountPrice: 0,
  title: '',
  condition: '',
  content: '',
  creatorId: authStore.uid,
  participantCount: 0,
  createTime: '',
  endTime: '',
  status: 'ongoing',
  description: '',
  createType:'admin',
});

const dialogVisible = ref(false);

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入调查标题', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
  unitPrice: [{ required: true, message: '请输入单价', trigger: 'blur' }],
  totalDiscountPrice: [{ required: true, message: '请输入总折扣价', trigger: 'blur' }],
  createTime: [{ required: true, message: '请选择创建时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 获取所有调查数据
const fetchSurveys = async () => {
  try {
    const response = await instance.get(props.isEnd ? '/surveys/end' : '/surveys');
    surveyData.value = response.data.data;
  } catch (error) {
    ElMessage.error('无法加载调查数据');
  }
};

// 创建调查
const createSurvey = async () => {
  try {
    const response = await instance.post('/surveys', surveyForm);
    ElMessage.success('调查创建成功');
    fetchSurveys();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('创建调查失败');
  }
};

// 更新调查
const updateSurvey = async () => {
  try {
    const response = await instance.put(`/surveys/${surveyForm.surveyId}`, surveyForm);
    ElMessage.success('调查更新成功');
    fetchSurveys();
    dialogVisible.value = false;
  } catch (error) {
    ElMessage.error('更新调查失败');
  }
};

// 删除调查
const deleteSurvey = async (surveyId: number) => {
  try {
    const response = await instance.delete(`/surveys/${surveyId}`);
    ElMessage.success('调查删除成功');
    fetchSurveys();
  } catch (error) {
    ElMessage.error('删除调查失败');
  }
};

// 编辑调查
const handleEdit = (row: Survey) => {
  surveyForm.surveyId = row.surveyId;
  surveyForm.amount = row.amount;
  surveyForm.quantity = row.quantity;
  surveyForm.unitPrice = row.unitPrice;
  surveyForm.totalDiscountPrice = row.totalDiscountPrice;
  surveyForm.title = row.title;
  surveyForm.condition = row.condition;
  surveyForm.content = row.content;
  surveyForm.creatorId = row.creatorId;
  surveyForm.participantCount = row.participantCount;
  surveyForm.createTime = row.createTime;
  surveyForm.endTime = row.endTime;
  surveyForm.status = row.status;
  surveyForm.description = row.description;
  surveyForm.createType = row.createType;
  dialogVisible.value = true;
};

const router = useRouter()
// 查看调查详情
const handleView = (row: Survey) => {
  router.push({ name: 'SurveyDetail', params: { surveyId:row.surveyId } });
  // surveyForm.surveyId = row.surveyId;
  // surveyForm.amount = row.amount;
  // surveyForm.quantity = row.quantity;
  // surveyForm.unitPrice = row.unitPrice;
  // surveyForm.totalDiscountPrice = row.totalDiscountPrice;
  // surveyForm.title = row.title;
  // surveyForm.condition = row.condition;
  // surveyForm.content = row.content;
  // surveyForm.creatorId = row.creatorId;
  // surveyForm.participantCount = row.participantCount;
  // surveyForm.createTime = row.createTime;
  // surveyForm.endTime = row.endTime;
  // surveyForm.status = row.status;
  // surveyForm.description = row.description;
  // dialogVisible.value = true;
};

// 创建按钮点击事件
const handleCreate = () => {
  surveyForm.surveyId = 0;
  surveyForm.title = '';
  surveyForm.amount = 0;
  surveyForm.quantity = 0;
  surveyForm.unitPrice = 0;
  surveyForm.totalDiscountPrice = 0;
  surveyForm.condition = '';
  surveyForm.content = '';
  surveyForm.creatorId = authStore.uid;
  surveyForm.participantCount = 0;
  surveyForm.createTime = '';
  surveyForm.endTime = '';
  surveyForm.status = 'ongoing';
  surveyForm.description = '';
  surveyForm.createType = "admin";
  console.log(surveyForm)
  dialogVisible.value = true;
};

// 提交表单
const submitForm = () => {
  if (surveyForm.surveyId === 0) {
    createSurvey();
  } else {
    updateSurvey();
  }
};

watch(() => props.isEnd,() => {
  fetchSurveys();
},{
  immediate:true,
})
</script>

<style scoped>
</style>
